<?
	session_start();
	error_reporting(E_ALL);
	include('conn.php');

	$qry1 = "SELECT CustId,socId,payamount,sum(payamount) as paid from payments group by CustId order by payid desc";
	$res1 = mysql_query($qry1);
	$data = array();
	$i = 0;

	 while($rows = mysql_fetch_array($res1))
	{
		$qry2 = "SELECT c.CustomerName,c.RoomNumber,s.societyname,sum(sc.RateperMonth) as totalrpm,
				sc.`TerminationDate`,sc.`ActivationDate`,
				sum(((period_diff(date_format((case when isnull(sc.`TerminationDate`) then now() 
				when ( sc.`TerminationDate` = '0000-00-00 00:00:00') then now() 
				else  sc.`TerminationDate` end),'%Y%m'),
				date_format(sc.`ActivationDate`,'%Y%m')) + 1) *  sc.`RateperMonth`)) AS `totalout`
				
				from Customer c, society s, STBtoCustomer sc
				where c.CustId = '".$rows['CustId']."' and s.socid = '".$rows['socId']."' and sc.CustId='".$rows['CustId']."';";	
				
		$res2 = mysql_query($qry2);
		$row2 = mysql_fetch_array($res2);
				
		$data[$i] = array
			(			
				"sid" => $rows['socId'],			
				"sname" => $row2['societyname'],			
				"room" => $row2['RoomNumber'],			
				"cid" => $rows['CustId'],			
				"cname" => $row2['CustomerName'],														
				"payamt" => $rows['payamount'],
				"paid" => $rows['paid'],
				"totalrpm" => $row2['totalrpm'],				
				"totalout" => $row2['totalout'],
				"currout" => $row2['totalout'] - $rows['paid']
			);		
		$i++;		
	}	
	echo json_encode($data);
?>